<?php

use yii\db\Schema;
use yii\db\Migration;

class m141028_062900_create_file_table extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%file}}', [
            'id' => Schema::TYPE_PK ,
            'user_id' => Schema::TYPE_INTEGER . ' unsigned NOT NULL DEFAULT 0',
            'uri' => Schema::TYPE_STRING . '(255) NOT NULL',
            'bundle' => Schema::TYPE_STRING . '(32) NOT NULL',
            'file_mime' => Schema::TYPE_STRING . '(255) NOT NULL',
            'file_size' => Schema::TYPE_BIGINT . ' UNSIGNED NOT NULL',
            'file_name' => Schema::TYPE_STRING . '(255) NOT NULL',
            'file_meta' => Schema::TYPE_BINARY . ' NOT NULL',
            'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 0',
            'created_at' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
            'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
            'KEY bundle_file (id, bundle)',
            'KEY user_id (user_id)',
            'KEY status (status)',
        ], $tableOptions);

        $this->createtable('{{%file_usage}}', [
            'file_id' => Schema::TYPE_INTEGER . ' unsigned NOT NULL',
            'object_id' => Schema::TYPE_INTEGER . ' unsigned NOT NULL',
            'bundle' => Schema::TYPE_STRING . '(32) NOT NULL',
            'field' => Schema::TYPE_STRING . '(32) NOT NULL',
            'weight' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
            'PRIMARY KEY (file_id, object_id, bundle, field)',
            'KEY file_list (object_id, bundle, field, weight)',
        ], $tableOptions);
    }

    public function down()
    {
        $this->dropTable('{{%file}}');
        echo "drop file table .\n";
        $this->dropTable('{{%file_usage}}');
        echo "drop file_usage table .\n";
    }
}
